package sqlClass.appClass;

import general.appClass.SystemInfo;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.SQLException;

import javax.imageio.ImageIO;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sqlClass.daoClass.DaoGet;


/**
 * Servlet implementation class BildDownApp
 */
@WebServlet("/ImgShowApp")
public class ImgShowApp extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ImgShowApp() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	/**
	 * @return 
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		response.setContentType("image/jpeg");
		response.setHeader("Pragma","No-Cache");
		response.setHeader("Cache-Control","No-Cache");
		response.setDateHeader("Expires", 0); 
		
		
		//System Information Manage Class
		Connection 	conn = SystemInfo.getConn(request);
		int bnr = Integer.parseInt(request.getParameter("bnr"));
		try {
				BufferedImage 	img 	= null;
				
				if(request.getParameter("type").equals("full_image")) 
					img = DaoGet.getPicDateById(conn, bnr, "full");
			
				if(request.getParameter("type").equals("middle_image"))
					img = DaoGet.getPicDateById(conn, bnr, "middle");
					
				if(request.getParameter("type").equals("thumb")) 
					img = DaoGet.getThumbDateById(conn, bnr);
				
				
				OutputStream os = response.getOutputStream();
				ImageIO.write(img, "jpg", os);
				os.flush();
				os.close();
		} catch (SQLException e) {
			e.printStackTrace();
			String message = e.getMessage();
			request.setAttribute("Quelle", "connect");
			request.setAttribute("Error", message);
			String url = response.encodeURL("/errorInfo.jsp");
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(url);
			dispatcher.forward(request,response);
		}
	}
}
